//
//  AppDelegate.swift
//  SwiftWeiBo
//
//  Created by LiCheng on 2017/2/8.
//  Copyright © 2017年 LiCheng. All rights reserved.
//

import UIKit
import UserNotifications
import SVProgressHUD
import AFNetworking

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {



        window = UIWindow()
        window?.backgroundColor = UIColor.white

        window?.rootViewController = LCMainViewController()

        window?.makeKeyAndVisible()


        setupDeploy()
        loadAppInfo()

        return true
    }
}

// MARK: - 项目配置
extension AppDelegate {

    fileprivate func setupDeploy() {

        // 1. 获取用户通知授权
        //    - 显示通知栏【上方提示条, 声音, badgeNumber】
        //    - iOS8.0以后需要用户授权
        //    - #available 是检测设备版本
        if #available(iOS 10.0, *) { // 10.0
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge, .carPlay]) { (success, error) in
                print("授权" + (success ? "成功" : "失败"))
            }
        } else { // 10.0以下
            let setting = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(setting)
        }

        // 2. 设置 SVP 最小显示时间
        SVProgressHUD.setMinimumDismissTimeInterval(2)

        // 3. 设置网络加载 状态栏指示器
        AFNetworkActivityIndicatorManager.shared().isEnabled = true
    }
}


// MARK: - 从服务器加载应用信息
extension AppDelegate {

    fileprivate func loadAppInfo() {

        // 1. 模拟异步
        DispatchQueue.main.async {

            // 1> url
            let url = Bundle.main.url(forResource: "main.json", withExtension: nil)

            // 2> data
            let data = NSData(contentsOf: url!)

            // 3> 写入磁盘
            let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let jsonPath = (docDir as NSString).appendingPathComponent("main.json")

            data?.write(toFile: jsonPath, atomically: true)

            print("加载成功\(jsonPath)")
        }
    }
}

